<template>
  <div class="productDetails">
    <CommonHeader title="商品详情">
      <template #left>
        <div>
          <Icon name="zuojiantou"></Icon>
          <span>返回</span>
        </div>
      </template>
    </CommonHeader>
    <div class="productDetailsImg" @click="previewImage">
      <CustomImage :src="productDetail.img" alt="" />
    </div>

    <!-- 商品详情 -->
    <div class="productDetailsContent">
      <div class="info">
        <div class="price">
          <p>商品价格:</p>
          <span>¥{{ productDetail.price }}</span>
          <span class="market_price">原价:{{ productDetail.market_price }}</span>
        </div>
        <div class="title">
          <p>商品名称:</p>
          <span>{{ productDetail.goodsname }}</span>
        </div>
        <div class="desc" v-html="productDetail.description"></div>
      </div>
    </div>
    <!-- 底部 客服 购物 店铺 加入购物车和立即购买按钮 -->
    <div class="bottom">
      <div class="bottom_item">
        <Icon name="kefu"></Icon>
        <span>客服</span>
        <span class="Unread"></span>
      </div>
      <div class="bottom_item cart" @click="goCart">
        <Icon name="gouwu"></Icon>
        <span>购物车</span>
        <span class="Unread" v-if="cartCount">{{ cartCount }}</span>
      </div>
      <div class="bottom_item">
        <Icon name="store"></Icon>
        <span>店铺</span>
        <span class="Unread">12</span>
      </div>
      <div class="bottom_item bottom_item_buy">
        <button class="bottom_item_btn" @click="productDetailsPopupActive = true">
          加入购物车
        </button>
        <button class="bottom_item_btn bottom_item_btn_buy" @click="gocart">立即购买</button>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div class="overlay" :class="{ active: productDetailsPopupActive }" @click="productDetailsPopupActive = false">
    </div>
    <!-- 点击后显示 商品选择弹窗 -->
    <div class="productDetailsPopup" :class="{ active: productDetailsPopupActive }">
      <div class="productDetailsPopup_header">
        <!-- 图片 -->
        <div class="productDetailsPopup_header_img" ref="imgRef">
          <!-- 抛出的球 -->
          <div class="ball">
            <div class="inner"></div>
          </div>
          <div class="img">
            <img :src="showImg" alt="" v-if="showImg" />
            <Icon name="tupianjiazaishibai" color="#ccc" size="30px" v-else></Icon>
          </div>
        </div>
        <!-- info -->
        <div class="info">
          <!-- 商品价格  -->
          <div class="price">
            <p>商品价格:¥{{ price }}</p>
          </div>
          <!-- 商品剩余  -->
          <div class="stock">
            <p>商品剩余: {{ number }} 件</p>
          </div>
          <!-- 请选择 颜色 内存 -->
          <div class="select">
            <div v-if="showColor || showMemory">
              <!-- 还没选完，显示请选择 -->
              <p>请选择:</p>
              <div class="select_item" v-if="showColor">
                <span>颜色</span>
              </div>
              <div class="select_item" v-if="showMemory">
                <span>内存</span>
              </div>
            </div>
            <div v-else>
              <!-- 颜色和内存都选了，显示已选择 -->
              <p>已选择: {{ color }} {{ memory }}</p>
            </div>
          </div>
        </div>
        <!-- 关闭按钮 -->
        <div class="close" @click="productDetailsPopupActive = false">
          <Icon name="close" color="#ccc"></Icon>
        </div>
      </div>
      <!-- 颜色选择 -->
      <div class="color">
        <p class="color_title">颜色:</p>
        <div class="color_content">
          <div class="color_item" v-for="item in colorList" :class="{ active: item.active }" :key="item.id"
            @click="changeColor(item)">
            <img :src="item.img" alt="" />
            <div class="color_item_icon">
              <Icon name="fangda" size="12px" color="#fff"></Icon>
            </div>
            <p>{{ item.name }}</p>
          </div>
        </div>
      </div>
      <!-- 内存选择 -->
      <div class="memory">
        <p class="memory_title">内存:</p>
        <div class="memory_content">
          <div class="memory_item" v-for="item in memoryList" :class="{ active: item.active }" :key="item.id"
            @click="changeMemory(item)">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>
      <!-- 购买数量 -->
      <div class="number">
        <p>购买数量:</p>
        <div class="number_content">
          <span class="number_minus" @click="numberNum--">-</span>
          <span class="number_num">{{ numberNum }}</span>
          <span class="number_plus" @click="numberNum++">+</span>
        </div>
      </div>
      <!-- 加入购物车和立即购买按钮 -->
      <div class="bottom_btn">
        <button class="bottom_item_btn" @click="addCart">加入购物车</button>
        <button class="bottom_item_btn bottom_item_btn_buy" @click="gocart">立即购买</button>
      </div>
    </div>
    <ImagePreview ref="imagePreview" :images="imageList" :initialIndex="0"></ImagePreview>
  </div>
</template>

<script>
import CommonHeader from '@/components/common/publicHeader/index.vue';

import Icon from '@/components/common/Icon/index.vue';

// 商品详情页
import { getGoodDetailAPI, addCartAPI } from '@/api/home';
import Toast from '@/utils/toast';
import ImagePreview from '@/components/common/ImagePreview/index.vue';
import CustomImage from '@/components/common/Image/index.vue';
export default {
  components: {
    CommonHeader,
    Icon,
    ImagePreview,
    CustomImage,
  },
  data() {
    return {
      isAnimating: false,
      // 轮播图数据
      banners: [
        {
          img: 'http://43.138.15.137:4000//uploads/banner/842bb270-8713-11f0-9b43-53be8531636c.jpg',
        },
        {
          img: 'http://43.138.15.137:4000//uploads/banner/3b2b81f0-8717-11f0-9b43-53be8531636c.jpg',
        },
        {
          img: 'http://43.138.15.137:4000//uploads/banner/986f1ff0-8723-11f0-9b43-53be8531636c.png',
        },
        {
          img: 'http://43.138.15.137:4000//uploads/banner/56426490-873a-11f0-9b43-53be8531636c.png',
        },
      ],
      // 图片列表
      // imageList: [],
      // 商品详情选择弹窗
      productDetailsPopupActive: false,

      // 商品详情
      productDetail: {},

      // 展示的图片
      showImg: '',
      // 剩余数量
      number: 1,
      // 是否选择了颜色
      showColor: true,
      // 颜色选择列表
      colorList: [
        {
          id: 1,
          name: '红色',
          img: '	https://img14.360buyimg.com/n0/jfs/t1/195251/28/503/70907/608a8bc4E87eaf1ae/9aa39ad669ed7f39.jpg',
          active: false,
          // 数量
          num: 200,
        },
        {
          id: 2,
          name: '蓝色',
          img: 'https://img14.360buyimg.com/n0/jfs/t1/131776/9/23287/325305/621f295fE9dc6a3ce/117b4d1ed262266a.jpg',
          active: false,
          // 数量
          num: 400,
        },
      ],
      // 价格
      price: 1000,
      // 内存选择列表
      showMemory: true,
      memoryList: [
        {
          id: 1,
          name: '4GB',
          active: false,
          // 价格
          price: 3200,
        },
        {
          id: 2,
          name: '8GB',
          active: false,
          // 价格
          price: 2000,
        },
      ],
      // 颜色
      color: '',
      // 内存
      memory: '',
      // 步进器数量
      numberNum: 1,
      // 购物车数量
      cartCount: null,
    };
  },
  mounted() {
    this.getGoodDetail();
  },
  methods: {
    // 手机颜色选择方法
    changeColor(item) {
      this.colorList.forEach(i => (i.active = false));
      item.active = true;
      this.showImg = item.img;
      this.number = item.num;
      this.color = item.name; // 记录选中的颜色名称
      this.showColor = false; // 这个变量你原来用于判断是否“已选”，我们保留
    },
    changeMemory(item) {
      this.memoryList.forEach(i => (i.active = false));
      item.active = true;
      this.price = item.price;
      this.memory = item.name; // 记录选中的内存名称
      this.showMemory = false;
    },
    // 请求
    async getGoodDetail() {
      try {
        const res = await getGoodDetailAPI({ id: this.$route.query.id });
        const { list } = res;
        this.productDetail = list[0];
        this.productDetail.img = 'http://43.138.15.137:4000/' + list[0].img;
      } catch (err) {
        console.log(err);
      }
    },

    // 添加购物车
    async addCart() {
      if (!this.color) {
        Toast('请选择颜色');
        return;
      }
      if (!this.memory) {
        Toast('请选择内存');
        return;
      }

      // ✅ 立即关闭弹窗
      this.productDetailsPopupActive = false;

      const imgEl = this.$refs.imgRef?.querySelector('.img');
      const cartIcon = document.querySelector('.cart');

      if (!imgEl || !cartIcon) return;

      // ✅ 克隆图片
      const cloneImg = imgEl.cloneNode(true);
      cloneImg.style.position = 'fixed';
      cloneImg.style.zIndex = '2001';
      cloneImg.style.width = '40px';
      cloneImg.style.height = '40px';
      cloneImg.style.borderRadius = '8px';
      cloneImg.style.overflow = 'hidden';
      cloneImg.style.pointerEvents = 'none';
      cloneImg.style.opacity = '1';

      const rect = imgEl.getBoundingClientRect();
      cloneImg.style.left = rect.left + 'px';
      cloneImg.style.top = rect.top + 'px';

      document.body.appendChild(cloneImg);

      // ✅ 目标偏移
      const cartRect = cartIcon.getBoundingClientRect();
      const dx = cartRect.left - rect.left;
      const dy = cartRect.top - rect.top;

      // ✅ 只动画 transform，opacity 保持 1
      cloneImg.style.transition = 'transform 1.2s cubic-bezier(0.5, -0.5, 1, 1)';
      cloneImg.style.transform = `translate(${dx}px, ${dy}px) scale(0.2)`;

      // ✅ 监听 transform 完成后再处理透明度
      const onTransitionEnd = () => {
        cloneImg.removeEventListener('transitionend', onTransitionEnd);

        // ✅ 关键：在这里，也就是“图片飞到购物车”的瞬间，再触发购物车动画
        if (cartIcon) {
          cartIcon.classList.add('cart-animate');
          const onAnimEnd = () => {
            cartIcon.removeEventListener('animationend', onAnimEnd);
            cartIcon.classList.remove('cart-animate');
        Toast.success('已加入购物车');

          };
          cartIcon.addEventListener('animationend', onAnimEnd);
        }

        // ✅ 然后才让克隆图片淡出消失
        cloneImg.style.transition = 'opacity 0.3s';
        cloneImg.style.opacity = '0';

        setTimeout(() => {
          if (document.body.contains(cloneImg)) {
            document.body.removeChild(cloneImg);
          }
        }, 300);
      };

      cloneImg.addEventListener('transitionend', onTransitionEnd);

      const onAnimEnd = () => {
        cartIcon.removeEventListener('animationend', onAnimEnd);
        cartIcon.classList.remove('cart-animate');
      };
      cartIcon.addEventListener('animationend', onAnimEnd);

      // ✅ 请求加入购物车
      const { uid } = JSON.parse(localStorage.getItem('userinfo'));
      try {
        const res = await addCartAPI({
          uid,
          goodsid: this.$route.query.id,
          num: this.numberNum,
        });
        const {
          list: { cartCount },
        } = res;
        this.cartCount = cartCount;
      } catch (err) {
        console.error(err);
      }
    },
    // 去购物车
    goCart() {
      this.$router.push({
        path: '/cart',
      });
    },
    // 预览图片
    previewImage() {
      this.$refs.imagePreview.openPreview();
    },
    // 去购物车
    gocart() {
      this.$router.push({
        path: '/cart',
      });
    },
  },
  computed: {
    imageList() {
      if (this.productDetail.img) {
        return this.productDetail.img.split(',')
      }
      return [];
    }
  }
};
</script>

<style lang="scss" scoped>
.productDetailsImg {
  width: 100%;
  height: 200px;

  img {
    width: 100%;
    height: 100%;
  }
}

.productDetailsContent {
  padding: 10px;
  position: relative;

  .info {
    .price {
      font-size: 14px;
      font-weight: bold;

      p {
        font-size: 14px;
        margin-right: 5px;
      }

      span {
        color: #ff4444;
        font-size: 16px;
      }

      .market_price {
        font-size: 12px;
        color: #999;
        text-decoration: line-through;
        margin-left: 5px;
      }
    }

    .title {
      font-size: 14px;
      font-weight: bold;

      p {
        font-size: 14px;
        margin-right: 5px;
      }

      span {
        font-size: 12px;
      }
    }

    // 穿透
    ::v-deep(.desc) {
      width: 100%;
      height: 300px;
      font-size: 14px;
      margin-top: 10px;

      .section {
        width: 100% !important;
        height: 100% !important;

        .section-plain_view {
          width: 100% !important;
          height: 100% !important;

          .img-box {
            width: 100% !important;
            height: 100% !important;
            overflow: visible;

            img {
              // 取消定位
              position: static !important;
              width: 100% !important;
              height: 100% !important;
              transform: none !important;
              border-radius: 10px;
            }
          }
        }
      }
    }

    .type {
      font-size: 14px;
      font-weight: bold;

      p {
        font-size: 14px;
        margin-right: 5px;
      }

      span {
        font-size: 12px;
      }
    }

    .specs {
      font-size: 14px;
      font-weight: bold;

      p {
        font-size: 14px;
        margin-right: 5px;
      }

      span {
        font-size: 12px;
      }
    }
  }
}

@keyframes cartBounce {
  0%   { transform: scale(1); }
  40%  { transform: scale(1.4); }  // 弹得更高一点
  70%  { transform: scale(0.9); }  // 压一下
  100% { transform: scale(1); }
}

.cart-animate {
  animation: cartBounce 0.4s ease-out;
}

.imgList {
  .imgList_item {
    width: 100%;
    height: 420px;

    img {
      width: 100%;
      height: 100%;
    }
  }
}

.bottom {
  position: fixed;
  padding: 0 10px;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  gap: 24px;
  z-index: 2;

  .bottom_item {
    flex-shrink: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #ccc;
    white-space: nowrap;
    position: relative;

    .Unread {
      position: absolute;
      top: 14px;
      right: 4px;
      min-width: 14px;
      height: 14px;
      padding: 0 2px;
      background-color: #ff4444;
      color: #fff;
      font-size: 10px;
      font-weight: bold;
      border-radius: 7px;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      line-height: 1;
      text-align: center;
      transform: translate(50%, -50%);
      box-sizing: border-box;

      /* 关键：隐藏空 span 的背景 */
      background-color: transparent;
    }

    /* 只有当 span 有文本内容时才显示红底和文字 */
    .Unread:not(:empty) {
      background-color: #ff4444;
      color: #fff;
      padding: 0 4px;
      min-width: 14px;
    }

    /* 当 span 为空时，用 ::before 画一个小红点 */
    .Unread:empty::before {
      content: '';
      position: absolute;
      width: 6px;
      height: 6px;
      background-color: #ff4444;
      border-radius: 50%;
      z-index: -1;
    }

    &.bottom_item_buy {
      flex: 1;
      flex-direction: row;
      overflow: hidden;
      gap: 10px;

      button {
        width: 100px;
        height: 40px;
        background-color: #f78855;
        color: #fff;
        font-size: 12px;
        padding: 0 10px;
        border-radius: 100px;
        font-weight: bold;

        &:nth-child(2) {
          background-color: #ff4444;
        }
      }
    }
  }
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 1000;
  transition: all 0.3s ease-in-out;
  visibility: hidden;
  opacity: 0;

  &.active {
    visibility: visible;
    opacity: 1;
  }
}

// 商品详情选择弹窗
.productDetailsPopup {
  position: fixed;
  bottom: -82%;
  left: 0;
  width: 100%;
  height: 82%;
  background-color: #fff;
  z-index: 2000;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  transition: all 0.3s ease-in-out;

  &.active {
    bottom: 0;
  }

  .productDetailsPopup_header {
    padding: 10px;
    display: flex;
    align-items: center;
    font-size: 14px;
    font-weight: bold;
    color: #333;
    border-bottom: 1px solid #ccc;
    position: relative;
    gap: 10px;

    .productDetailsPopup_header_img {
      width: 90px;
      height: 90px;
      border-radius: 10px;
      text-align: center;
      line-height: 90px;
      position: relative;
      background-color: #f5f5f5;

      .ball {
        position: absolute;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        right: 0;
        top: 0;
        pointer-events: none;
        opacity: 0;
        // transition: transform 2s cubic-bezier(0.5, -1, 1, 1);
        transition: transform 1.5s cubic-bezier(0.5, -1, 1, 1), opacity 0.3s;
        transform: translate(0, 0);
        z-index: 2025;
      }

      .inner {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #ff4444;
      }

      @keyframes movex {
        to {
          transform: translate(-200px);
        }
      }

      @keyframes movey {
        to {
          transform: translateY(200px);
        }
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .info {
      flex: 1;
      height: 70px;
      font-size: 12px;
      display: flex;
      justify-content: space-between;
      flex-direction: column;

      .price {
        font-size: 14px;
        font-weight: bold;
        color: #ff4444;
      }

      .stock {
        p {
          font-size: 12px;
          font-weight: bold;
          color: #ccc;
        }
      }

      .select {
        display: flex;
        color: #ccc;
        gap: 10px;

        div {
          display: flex;
          gap: 10px;
        }
      }
    }

    .close {
      position: absolute;
      top: 10px;
      right: 12px;
      font-weight: bold;
      color: #333;
    }
  }

  .color {
    padding: 10px;
    font-size: 14px;
    font-weight: bold;
    color: #333;

    .color_title {
      font-size: 14px;
      font-weight: bold;
      color: #333;
      margin-bottom: 10px;
    }

    .color_content {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 10px;
      padding: 0 5px;

      .color_item {
        width: 120px;
        position: relative;
        text-align: center;
        border-radius: 5px;
        overflow: hidden;

        &.active {
          border: 1px solid #ff4444;

          p {
            color: #ff4444;
            background-color: #ffe9ea;
          }
        }

        img {
          width: 100%;
          height: 82%;
          margin-bottom: 4px;
          border-radius: 5px;
        }

        .color_item_icon {
          position: absolute;
          top: 0;
          right: 0;
          width: 20px;
          height: 20px;
          background-color: #999;
          border-top-right-radius: 5px;
          border-bottom-left-radius: 5px;
        }

        p {
          width: 100%;
          height: 35px;
          font-size: 12px;
          background-color: #f7f8fa;
          line-height: 35px;
        }
      }
    }
  }

  .memory {
    padding: 10px;
    font-size: 14px;
    font-weight: bold;
    color: #333;

    .memory_title {
      font-size: 14px;
      font-weight: bold;
      color: #333;
      margin-bottom: 10px;
    }

    .memory_content {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 10px;
      padding: 0 5px;

      .memory_item {
        padding: 8px;
        position: relative;
        background-color: #f7f8fa;
        text-align: center;
        border-radius: 5px;
        font-size: 14px;
        transition: all 0.3s ease-in-out;

        &.active {
          background-color: #ff4444;
          color: #fff;
        }
      }
    }
  }

  .number {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    gap: 10px;
    font-size: 14px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;

    .number_content {
      width: 90px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 2px;
      border-radius: 4px;
      overflow: hidden;

      .number_minus,
      .number_plus,
      .number_num {
        width: 35px;
        height: 28px;
        line-height: 28px;
        font-size: 12px;
        text-align: center;
        background-color: #f2f3f5;
      }
    }
  }

  .bottom_btn {
    width: 90%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 14px;
    font-weight: bold;
    display: flex;
    align-items: center;
    overflow: hidden;
    border-radius: 20px;
    margin: 40px auto 0;

    .bottom_item_btn {
      flex: 1;
      height: 100%;
      color: #fff;
      background-color: #ffc61c;

      &.bottom_item_btn_buy {
        background-color: #f11927;
      }
    }
  }
}
</style>
